class readFrame {
  constructor(_vscode) {
    this.vscode = _vscode
    this.selectLine = 0
    this.init()
    this.lang = 'vue'
    this.langSub = 'stylus'
  }
  init() {
    console.log('i will read this field\'s frame')
    // this.vscode.window.showInformationMessage('i will read the dom tree what you selece');
    this.vscode.window.setStatusBarMessage('正在解析页面结构 | styleFrame rendering...');
    // handle
    // console.log(this.selectContent())
    this.renderDom()
  }
  selectContent() {
    let content = this.vscode.window.activeTextEditor._documentData._lines
    let select = [this.vscode.window.activeTextEditor.selection.start.line, this.vscode.window.activeTextEditor.selection.end.line + 1]
    let result = ''
    this.vscode.window.setStatusBarMessage(`选择行数:${select[1]-select[0]} | lines`);
    this.selectLine = select[1] - select[0]
    for (let i = select[0]; i < select[1]; i++) {
      const element = content[i];
      result = result + element
    }
    // 处理jsx
    if (result.match('className')) {
      this.lang = 'react'
      this.langSub = 'scss'
      this.vscode.window.setStatusBarMessage('解析并复制成功 | 当前语言：' + this.lang + '&' + this.langSub);
      return result.replace(/className/g, 'class')
    } else {
      this.lang = 'vue'
      this.langSub = 'stylus'
      this.vscode.window.setStatusBarMessage('解析并复制成功 | 当前语言：' + this.lang + '&' + this.langSub);
      return result
    }
  }
  renderDom() {
    // console.log(this.vscode.ViewColumn)
    const panel = this.vscode.window.createWebviewPanel(
      'testWebview', // viewType
      "styleFrame", // 视图标题
      this.vscode.ViewColumn.Beside, // 显示在编辑器的哪个部位
      {
        enableScripts: true, // 启用JS，默认禁用
        retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
      }
    );
    // 关闭 webview
    setTimeout(() => {
      panel.dispose()
      if (this.selectLine > 25) {
        this.vscode.window.setStatusBarMessage('解析完成但行数太多会导致格式化失败 | too many lines!');
        return
      }
      // this.vscode.window.setStatusBarMessage('解析并复制成功 | 当前语言：' + this.lang + '&' + this.langSub);
    }, 1800);

    //页面渲染
    panel.webview.html = `
    <div class="frame" style="display:none">${this.selectContent()}</div>
    <div id="styleFrame"></div>
    <script>
      class DomTree {
        constructor(dom) {
          this.domRoot = dom
          this.tree = {}
          this.init()
        }
        init() {
          this.renderDom()
        }
        traver(dom, branch) {
          for (let i = 0; i < this.picker(dom).length; i++) {
            const element = this.picker(dom)[i];
            if (element.nodeType === 1) {
              let branchName = element.tagName.toLowerCase()
              if (element.className) {
                branchName = '.' + element.className
              }
              if (element.childNodes.length > 1 || (element.childNodes.length === 1 && element.childNodes[0].nodeType ===
                  1)) {
                if (typeof branch[branchName] != 'object') branch[branchName] = {}
                this.traver(element, branch[branchName])
              } else {
                if (!branch[branchName]) branch[branchName] = '{}'
              }
            }
          }
        }
        picker(dom) {
          let doms = []
          for (let i = 0; i < dom.childNodes.length; i++) {
            const element = dom.childNodes[i];
            if (element.nodeType === 1 && !element.nodeName.match('STYLE') && !element.nodeName.match('SCRIPT')) {
              doms.push(element)
            }
          }
          return doms
        }
        transform(root, obj) {
          let lang = '${this.lang}'
          console.log('语言：' + lang)
          let result = '_' + JSON.stringify(obj).replace(/\"/g, '').replace(/\,/g, ';') + '_'
          result = result.split('_{')[1].split('}_')[0]
          if (lang === 'react') {
            result = result.replace(/\:|\;/g, '')
          }
          return result
        }
        renderDom() {
          this.picker(this.domRoot)
          this.traver(this.domRoot, this.tree)
          this.toClipBoard(this.transform('body', this.tree))
          document.querySelector('#styleFrame').parentNode.innerHTML = 'rendering...😁'
        }
        toClipBoard(e) {
          const input = document.createElement('input');
          document.body.appendChild(input);
          input.setAttribute('value', e);
          input.select();
          if (document.execCommand('copy')) {
            document.execCommand('copy');
            console.log('render succeed');
          }
          document.body.removeChild(input);
        }
      }
      let domTree = new DomTree(document.querySelector('.frame'))
    </script>
    `
    console.log(panel.webview)
  }
}
module.exports = readFrame